package com.neisha.kit;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public final class HttpKit {
	
	private static final Logger loggers = LoggerFactory.getLogger(HttpKit.class);
	
	public static String get(String url,String charSet) throws HttpException{
		try {
			 URL realUrl = new URL(url);
		     // 打开和URL之间的连接
		     URLConnection conn = realUrl.openConnection();
		     // 设置通用的请求属性
		     conn.setRequestProperty("accept", "*/*");
		     conn.setRequestProperty("connection", "Keep-Alive");
		     conn.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
		     conn.setReadTimeout(60*1000); // 1分钟
		    String result = "";
		    // 定义BufferedReader输入流来读取URL的响应
		    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(),charSet));
		    String line;
		    while ((line = in.readLine()) != null) {
		        result += line;
		    }
		    in.close();
		    return result;
		} catch (Exception e) {
			loggers.error("http get url error.",e);
			throw new HttpException(e.fillInStackTrace());
		}
	}
	
	public static String get(String url) throws HttpException{
		return get(url,"utf-8");
	}

}
